import { Button, createTheme, Paper, TextField } from "@mui/material";
import { Box } from "@mui/system";
import React, { useContext } from "react";
import { useState } from "react";
import VerPng from "../../components/VerPng";
import useVrLogin from "../../query/useVrLogin";
import SendIcon from "@mui/icons-material/Send";
import { useEffect } from "react";
import useEmail from "../../query/useEmail";
import { useSnackbar } from "notistack";
import LoadingButton from "../../components/LoadingButton";
import { useMutation } from "@tanstack/react-query";
import { postQueryFn } from "../../query/postQueryFn";
import { green } from "@mui/material/colors";
import { VR_EMAIL_URL } from "../../constants/url";
import { ThemeColorContext, UserContext } from "../../App";
import getLocalUser from "../../api/getUser";
import { useNavigate } from "react-router-dom";
import { useMemo } from "react";
import { ThemeProvider } from "@emotion/react";
export default function Activation() {
  const [verToken, setVerToken] = useState();
  const [changeVr, setChangeVr] = useState(false);
  const [vertifyCode, setVertifyCode] = useState();
  const [email, setEmail] = useState();
  const [mysendSuccess, setSendsuccess] = useState(false);
  const [emailVr, setEmailVr] = useState();
  const {
    isSuccess: VrSuccess,
    isError: VrIsError,
    mutate: vrMutate,
    data: VrData,
    isLoading: VrIsLoading,
  } = useVrLogin();
  const { enqueueSnackbar } = useSnackbar();

  const handleVr = () => {
    if (email == "" || email == null) {
      setEmail("");
      setVertifyCode("");
      return;
    }
    vrMutate({ vertifyCode, verToken });
  };
  const {
    isLoading: sendLoading,
    mutate: sendMutate,
    isError: sendError,
    isSuccess: sendSuccess,
  } = useEmail();

  useEffect(() => {
    if (VrSuccess) {
      if (VrData.data.code == 0) {
        sendMutate({ email: email });
      } else {
        setChangeVr(!changeVr);
      }
    }
  }, [VrSuccess]);
  useEffect(() => {
    if (sendSuccess) {
      //
      setChangeVr(!changeVr);
      setSendsuccess(true);
      setTimeout(() => setSendsuccess(false), 1500);
    }
  }, [sendSuccess]);

  const {
    data: resData,
    isFetching: resFetching,
    isSuccess: resSuccess,
    mutate: emailVrMutate,
  } = useMutation(["bindemail"], postQueryFn);

  const handleEmailVr = () => {
    if (emailVr == null || emailVr == "") {
      setEmailVr("");
      return;
    }
    emailVrMutate({
      params: {
        code: emailVr,
      },
      Key: [
        VR_EMAIL_URL,
        {
          useToken: true,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        },
      ],
    });
  };
  const navigate = useNavigate();
  const user = useContext(UserContext); //角色context
  const themeColor = useContext(ThemeColorContext);
  useEffect(() => {
    if (resSuccess) {
      enqueueSnackbar("绑定成功", { variant: "success" });
      themeColor.setThemeColor(getLocalUser());
      user.setUser(getLocalUser());
      navigate("/index/login");
    }
  }, [resSuccess]);
  const innerTheme = useMemo(() =>
    createTheme({
      palette: {
        mode: "light",
      },
    })
  );
  return (
    <ThemeProvider theme={innerTheme}>
      <Box
        sx={{
          display: "flex",
          flexDirection: "row",
          justifyContent: "center",

          width: "100%",
        }}
      >
        <Paper
          elevation={4}
          sx={{
            padding: "20px 30px",
            width: "70%",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            marginTop: "100px",
            minWidth: "600px",
          }}
        >
          <TextField
            error={sendError || email == ""}
            helperText={
              sendError
                ? "*请输入正确邮箱"
                : email == ""
                ? "请输入邮箱地址"
                : null
            }
            fullWidth
            label="email"
            variant="outlined"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            sx={{ marginBottom: 3, maxWidth: "400px" }}
          />
          <TextField
            error={VrData?.data?.code == 40108 || vertifyCode == ""}
            fullWidth
            label="图片验证码"
            helperText={
              VrData?.data?.code == 40108
                ? "*验证码错误"
                : vertifyCode == ""
                ? "*请输入验证码"
                : null
            }
            value={vertifyCode}
            onChange={(e) => {
              setVertifyCode(e.target.value);
            }}
            variant="outlined"
            sx={{ maxWidth: "400px" }}
          />
          <VerPng key={changeVr} s={setVerToken} />
          <LoadingButton
            showRight={true}
            titler={mysendSuccess ? "发送成功" : "发送邮箱验证码"}
            endIcon={<SendIcon />}
            clickr={handleVr}
            isFetching={sendLoading}
            isSuccess={mysendSuccess}
          />

          <TextField
            error={resData?.data.code == 40108 || emailVr == ""}
            fullWidth
            label="邮箱验证码"
            helperText={
              resData?.data?.code == 40108
                ? "*验证码错误"
                : emailVr == ""
                ? "*请输入验证码"
                : null
            }
            value={emailVr}
            onChange={(e) => {
              setEmailVr(e.target.value);
            }}
            variant="outlined"
            sx={{ maxWidth: "400px", margin: "20px 0" }}
          />

          <Button variant="contained" onClick={handleEmailVr}>
            保存
          </Button>
        </Paper>
      </Box>
    </ThemeProvider>
  );
}
